package com.hall.service;

import com.hall.dao.TencentCosMapper;
import com.hall.pojo.SysUser;
import com.hall.pojo.common.Result;
import com.hall.utils.TencentCloudUtils;
import com.hall.utils.TencentMessageUtils;
import com.hall.utils.UserSession;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class TencentCosServiceImpl implements TencentCosService{
    @Autowired
    private TencentCosMapper tencentCosMapper;
    @Autowired
    private UserService userService;
    private String secretId="AKIDOfmlYCPQEqHXb7PTJwKWWJrBJGApHbhZ";


    private String secretKey="g7JI4eCUZSEn8E5lLq8B2f5IDvPp5A2p";


    private String region="ap-shanghai";


    private String bucketName="bokehall-1310510006";

    private String path="https://bokehall-1310510006.cos.ap-shanghai.myqcloud.com/";//注意后缀不要忘记"/"
    //水印,字体,间距等参数,如需要请根据开发文档修改
    private String otherConfig = "?ci-process=doc-preview&dstType=html&htmlwaterword=576k54ix5pm65oWn5Yy755aX&htmlvertical=40&htmlfront=Ym9sZCA0MHB4IFNlcmlm&htmlfillstyle=cmdiYSgyNTUsMTQ0LDE0NCwwLjcp";
    @Override
    public Result upload(MultipartFile file, String appointment_id,String user_id, String report_id, String report_time, String clientfilename, String clientfiletype, String filepath, HttpServletRequest request) {
        if(file==null){
            return Result.error("未提交文件,请重试");
        }
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的区域, COS 地域的简称请参照
        Region regions = new Region(region);
        ClientConfig clientConfig = new ClientConfig(regions);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        try {
            String originalfileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 3);
            // 获得文件流
            InputStream inputStream = file.getInputStream();
            //设置文件key
            String filePath = "meet/";
            String datePath = new DateTime().toString("yyyy/MM/dd");///
            originalfileName= filePath+datePath+"/"+uuid+originalfileName;
            filePath = originalfileName;
            // 上传文件
            cosClient.putObject(new PutObjectRequest(bucketName, filePath, inputStream, null));
            cosClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            String url = path + "/" + filePath;
            Map<String, String> map = new HashMap<>();
            map.put("fileName", originalfileName); //文件路径
            map.put("url", url);        //访问路径
            String id = UUID.randomUUID().toString().replace("-",""); //主键uuid
            SysUser sys =userService.getUser(user_id); //当前登录用户
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            int state = tencentCosMapper.uploadFile(id,appointment_id,clientfilename,clientfiletype,originalfileName,sys.getId(),sys.getName(),report_id,report_time);
            if(state>0){
                return Result.success(map,"请求成功并返回数据");
            }else{
                return Result.error("上传失败,请重试(文件不能为空,或文件大小超过200m)");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        return Result.error("上传失败,请重试(文件不能为空,或文件大小超过200m)");
    }
    @Override
    public Result download(String id) {

        String paths = tencentCosMapper.downLoad(id);
        return paths!=null? Result.success(path+paths, "请求成功"):Result.success(null, "请求失败,无符合的文件");
    }
    @Override
    public String previewFile(String filePath) {
        String suffix = filePath.substring(filePath.lastIndexOf(".") + 1).toLowerCase();//获取文件的后缀名,并统一转小写
        System.out.println("后缀为"+suffix);
        if ("jpg".equals(suffix) || "png".equals(suffix)|| "jpeg".equals(suffix)|| "gif".equals(suffix)||"bmp".equals(suffix)) {
            return path + filePath;   //如果是图片文件
        } else {
            return path + filePath + otherConfig; //其他文件
        }
    }
    @Override
    public String delete(){
        return null;
    }
    public void setTencentCosMapper(TencentCosMapper tencentCosMapper) {
    }
}
